<template>
  <div class="create-box">
    <div class="item" @click="show">
      <el-button
          text
          @click="show"
          bg
          style="font-family: dingding;font-size: 2vh"
      >
        发起流程
      </el-button>
    </div>
  </div>


  <div class="shade" v-if="isShadeShow" data-aos="fade-left"></div>

  <div class="form" data-aos="fade-left" v-if="isShadeShow">
    <div class="form-title">
      请假申请
    </div>
    <div class="leave-form">
      <el-form
          ref="ruleFormRef"
          style="max-width: 60vw"
          :model="leave_form"
          label-width="auto"
          class="demo-ruleForm"
          size="default"
          status-icon
      >
        <el-form-item label="起止时间" class="el-form-items">
          <div class="block">
            <el-date-picker
                v-model="leave_form.time"
                type="daterange"
                range-separator="至"
                start-placeholder="选择起始时间"
                end-placeholder="选择结束时间"
                size="default"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </div>
        </el-form-item>
        <el-form-item label="请假天数" class="el-form-items">
          <el-input v-model="leave_form.days" style="width: 240px" placeholder="请假天数" disabled />
        </el-form-item>
        <el-form-item label="请假事由" class="el-form-items">
          <el-input
              v-model="leave_form.reason"
              style="width: 240px"
              :rows="2"
              type="textarea"
              placeholder="请输入请假事由"
          />
        </el-form-item>
        <el-form-item label="审核人员" class="el-form-items">
          <el-cascader
            v-model="leave_form.operator"
            :options="options"
            :show-all-levels="false"
            @change="handleChange1"
            placeholder="请选择审核人"
          />
        </el-form-item>
        <el-form-item label="抄送人员" class="el-form-items">
          <el-cascader
            v-model="leave_form.copy"
            :options="options"
            :show-all-levels="false"
            @change="handleChange2"
            placeholder="请选择抄送人"
          />
        </el-form-item>
        <div class="btn-box" style="margin-top: 3vh;">
          <el-button type="primary" @click="submitForm">
            提交
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
  <div class="close-btn" @click="closeForm" data-aos="fade-left" v-if="isShadeShow">
    <span>关</span>
    <span>闭</span>
  </div>

  <CreateFinance ref="createFinanceRef"/>
</template>

<script setup>
import {Briefcase, List, Stamp, WalletFilled,} from "@element-plus/icons-vue"
import {ElButton, ElDatePicker, ElForm, ElMessage} from "element-plus"
import {onMounted, reactive, ref, watch} from "vue"
import emitter from "@/lib/eventBus"
import {checkUserByRole, submitFlow, getLeaveFlowList} from "@/api"
import {getTime} from "@/lib/utils.js"
import CreateFinance from "@/components/Finance/Bill/CreateFinance.vue"

//遮罩层
const isShadeShow = ref(false)
//级联选择
const options = ref([])
//请假表单
let leave_form = reactive({
  time : '',
  days : 0,
  reason : '',
  operator : '',
  copy : '',
  starting_date:'',
  termination_date:'',
})
//表单校验规则
const ruleFormRef = ref()

//用户信息
let user_info
//遮罩层
const users = ref([])
//时间戳
let now

const createFinanceRef = ref()

onMounted(()=>{
  getUserInfo()
  AOS.init()
  // 监听请假页面的显隐
  emitter.on('showLeave',(t) => {
    isShadeShow.value = t
    console.log(123)
  })
  getUserList()
  now = getTime()
})

//获取用户信息
const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}


//获取级联用户列表
// const getUserList = async () => {
//   try {
//     let rolename = []
//     let roleUser = []
//     const {data:res} = await checkUserByRole()
//
//     const values = Object.values(res.data)
//     values.forEach(value => {
//       let datas = Object.values(value)
//       datas.forEach(data => {
//         if(typeof data === "string"){
//           rolename.push(data)
//         } else {
//           roleUser.push(data)
//         }
//       })
//     })
//     console.log(roleUser)
//     for (let i = 0; i < 9; i++){
//       options.value.push({
//         label:rolename[i],
//         value:null,
//         children:[]
//       })
//       console.log(roleUser[8])
//       for (let j = 0; j < roleUser[i].length; j++){
//         options.value[i].children.push({
//               label:roleUser[i][j].user_name,
//               value:roleUser[i][j].user_id,
//             }
//         )
//       }
//     }
//   } catch (e) {
//     console.log(e)
//   }
// }
const getUserList = async () => {
  try {
    let rolename = [];
    let roleUser = [];
    const { data: res } = await checkUserByRole();

    const values = Object.values(res.data);
    values.forEach(value => {
      let datas = Object.values(value);
      datas.forEach(data => {
        if (typeof data === "string") {
          rolename.push(data);
        } else {
          roleUser.push(data);
        }
      });
    });
    console.log(roleUser);

    for (let i = 0; i < roleUser.length; i++) {
      options.value.push({
        label: rolename[i],
        value: null,
        children: []
      });
      if (roleUser[i] && roleUser[i].length > 0) {
        for (let j = 0; j < roleUser[i].length; j++) {
          options.value[i].children.push({
            label: roleUser[i][j].user_name,
            value: roleUser[i][j].user_id,
          });
        }
      }
    }
  } catch (e) {
    console.log(e);
  }
};

//遮罩层显隐
const show = () => {
  // isShadeShow.value = !isShadeShow.value
  isShadeShow.value = true
}

//重置表单
const resetForm = (formEl) => {
  formEl.resetFields()
}


//关闭、重置表单
const closeForm = () => {
  leave_form.time=''
  leave_form.days=''
  leave_form.reason=''
  leave_form.operator=''
  leave_form.copy=''
  leave_form.starting_date=''
  leave_form.termination_date=''
  isShadeShow.value = false
}

/*请假表单*/
const submitForm = async () => {
  try {
    if(!leave_form.time || !leave_form.reason || !leave_form.operator){
      return ElMessage({
        message:'请正确填写信息',
        type:'warning'
      })
    } else if(leave_form.operator[leave_form.operator.length-1] === leave_form.copy[leave_form.copy.length-1]) {
      return ElMessage({
        message:'审批人和申请人不能为同一人',
        type:'warning'
      })
    } else if (leave_form.operator[leave_form.operator.length-1] === user_info.id || leave_form.copy[leave_form.copy.length-1] === user_info.id){
      return ElMessage({
        message:'审批人和申请人不能为自己',
        type:'warning'
      })
    }
    const {data:res} = await submitFlow({
      userId:user_info.id,
      operatorId:leave_form.operator[leave_form.operator.length-1],
      flowType:0,
      action:1,
      flow_detail:leave_form.reason,
      starting_date:leave_form.time[0],
      termination_date:leave_form.time[1],
      uploader_name:user_info.username,
      copyId:leave_form.copy[leave_form.copy.length-1],
      total_days:leave_form.days,
    })
    if(res.code === 200) {
      await emitter.emit('reload')
      ElMessage({
        message:'流程发起成功!',
        type:'success'
      })
      setTimeout(()=>{
        closeForm()
      },1000)
    } else {
      ElMessage({
        message:'流程发起失败!',
        type:'error'
      })
      setTimeout(()=>{
        closeForm()
      },1000)
    }
  } catch (e) {
    console.log(e)
  }
}

const handleChange1 = () => {
  console.log(leave_form.operator[leave_form.operator.length-1])
}

const handleChange2 = () => {
  console.log(leave_form.copy[leave_form.copy.length-1])
}

const computeDate = (day1,day2) => {
  let start = new Date(day1);
  let end = new Date(day2);
  let workdayCount = 0;
  for (let date = start; date <= end; date.setDate(date.getDate() + 1)) {
    //Date 对象的 getDay() 方法可以获取日期对应的星期几，返回值范围是 0 到 6，分别代表周日到周六。
    if (date.getDay() >= 1 && date.getDay() <= 5) {
      workdayCount++;
    }
  }
  return workdayCount
}


const createFinance = () => {
  createFinanceRef.value.show()
}

watch(() => leave_form.time,()=>{
  leave_form.days = computeDate(leave_form.time[0],leave_form.time[1]) ? computeDate(leave_form.time[0],leave_form.time[1]) : 0
})


watch(()=>leave_form.operator,()=>{
  // if (leave_form.operator[0] === null){
  //   leave_form.operator = []
  //   ElMessage({
  //     message:'不能选择部门作为审核人',
  //     type:'error'
  //   })
  // }
})

</script>

<style scoped lang="less">
.create-box{
  height: 4vh;
  width: 5vw;
  //background-color: pink;
  position: absolute;
  z-index: 999;
  left: 90vw;
  top: 3vh;
  font-size: 2vh;
  line-height: 4vh;
  font-family: dingding;
}
.shade{
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 800;
  left: 3vw;
  background-color: rgba(0,0,0,.7);
}
.form{
  position: absolute;
  left: 26vw;
  z-index: 950;
  height: 100vh;
  width: 74vw;
  background-color: white;
  padding: 20px;
  box-sizing: border-box;
  background-color: rgba(250, 250, 250);
  .form-title{
    text-align: left;
    font-size: 2.2vh;
    font-weight: 600;
    letter-spacing: 1px;
    padding-left: 2vh;
    margin-top: 1vh;
  }
  .leave-form{
    margin-top: 1vh;
    .el-form{
      padding: 2vh;
      .el-form-items{
        border: 1px solid rgba(238, 238, 238);
        margin: 0 !important;
        //background-color: ;
        height: 8vh;
        align-items:center;
        justify-content: center;
        .el-form-item--default .el-form-item__label {
        }
        :deep(.el-form-item__label-wrap) {
          width: 10vw;
          line-height: 8vh;
          height: 8vh;
          text-align: center;
          box-sizing: border-box;
          border-right: 1px solid rgba(238, 238, 238);
          &:last-child {
            border-right: none;
          }
        }
        :deep(.el-form-item__label){
          padding: 0 !important;
          margin: auto !important;
        }
        :deep(.el-range-editor.el-input__wrapper){
          width: 45vw;
          margin-left: 3vw;
        }
        :deep(.el-input) {
          width: 46vw !important;
          margin-left: 3vw;
        }
        :deep(.el-textarea ){
          width: 46vw !important;
          margin-left: 3vw;
        }

      }
    }
  }
}
.close-btn{
  position: absolute;
  top: 15vh;
  left: 24vw;
  height: 9vh;
  width: 3.5vw;
  z-index: 899;
  background-color: rgba(255, 87, 34);
  margin: 1vh auto;
  border: 2px solid white;
  box-sizing: border-box;
  border-radius: 5px;
  display: flex;
  justify-content: space-around;
  color: white;
  flex-direction: column;
  padding-left: 0.5vw;
  align-items: start;
  font-size: 1.6vh;
  &:hover{
    cursor: pointer;
  }
}
:deep(.el-form-item--default .el-form-item__content) {
  line-height: 32px;
  height: 8vh;
  background-color: #fff;
}
</style>
